<template>
  <div>
    <el-form
      :model="userForm"
      :rules="rules"
      ref="userForm"
      label-width="80px"
    >
      <el-form-item
        label="昵称"
        prop="nickname"
      >
        <el-input
          placeholder="请输入昵称"
          v-model="userForm.userName"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="性别"
        prop="sex"
      >
        <el-radio-group v-model="userForm.sex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
          <el-radio label="2">保密</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="个性签名"
        prop="motto"
      >
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入个性签名"
          v-model="userForm.motto"
          maxlength="30"
          show-word-limit
        >
        </el-input>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button @click="cancelSubmit">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="submitForm('userForm')"
      >
        确认提交
      </el-button>
    </div>
  </div>
</template>

<script>
import { updateUsersInfo } from '@/api/user'
export default {
  name: 'InfoForm',
  props: {
    userInfo: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      userForm: {
        userName: this.userInfo.userName,
        sex: this.userInfo.sex,
        motto: this.userInfo.motto
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 12, message: '长度为2-12个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              var MobileRegex = /^1[34578]\d{9}$/
              if (MobileRegex.test(value)) {
                callback(new Error('用户名不可以是手机号！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    reset () {
      this.userForm = {
        userName: this.userInfo.userName,
        sex: this.userInfo.sex,
        motto: this.userInfo.motto
      }
    },
    // 取消提交
    cancelSubmit () {
      this.$emit('cancel')
    },
    // 提交修改表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleUpdateUserInfo()
        } else {
          return false
        }
      })
    },
    async handleUpdateUserInfo () {
      this.loading = true
      await updateUsersInfo(this.userForm)
      this.loading = false
      this.$message.success('信息修改成功')
      this.$emit('submit')
    }
  }
}
</script>
